package scheduleManage

import (
	"github.com/go-xorm/xorm"
	"github.com/martini-contrib/encoder"
	"hotel_Manager_Api/util"
)


func GetAlldeskOrderSchedules(enc encoder.Encoder, db *xorm.Engine) []byte {
	result := make([]DeskOrderSchedule, 0)
	db.SQL(getDeskOrdersSql()).Find(&result)
	return encoder.Must(enc.Encode(result))
}

func NewSchedule(order DeskOrderScheduleRequst,db *xorm.Engine,generator util.IdGenerator) int {
	orderEntity,schedule,orders:= order.toDbEntities(generator)
	session := db.NewSession()
	defer session.Close()

	session.Begin()
	_,err := session.Insert(orderEntity)
	if(err!=nil){
		return 500
	}
	_,err =session.Insert(schedule)
	if(err!=nil){
		return 500
	}
	_,err =session.Insert(orders)
	if(err!=nil){
		return 500
	}
	err = session.Commit()
	if(err!=nil){
		return 500
	}
	return 201
}

func getDeskOrdersSql() string {
	sql := `SELECT desk.id as deskId,desk.floor,desk.name,desk.chairCount,desk_order.id as deskOrderId,desk_order.dinnerTime,desk_order.orderStatus,schedule_order.beginTime,schedule_order.endTime FROM hotelmanager.desk
			left join desk_order on desk.id = desk_order.deskId
			left join schedule_order on desk_order.id = schedule_order.deskOrderId`
	return sql
}
